package com.examination.controller.staffModel;

import com.examination.controller.uploadModel.UploadController;
import com.examination.entity.*;
import com.examination.service.checkModel.ExamRecordService;
import com.examination.service.staffModel.BehaviorRecordService;
import com.examination.service.staffModel.StaffService;
import com.examination.service.staffModel.WorktypeService;
import com.examination.service.trainModel.TrainContentRecordService;
import com.examination.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(description = "员工接口")
@RestController
@RequestMapping("staff")
@CrossOrigin
public class StaffController {
    @Autowired
    private StaffService staffService;//员工

    @Autowired
    private WorktypeService worktypeService;//工种

    @Autowired
    private BehaviorRecordService behaviorRecordService;

    @Autowired
    private ExamRecordService examRecordService;

    @Autowired
    private TrainContentRecordService trainContentRecordService;

    @ApiOperation(value = "增加员工信息", notes = "")
    @PostMapping("/InsertStaff")
    public JsonResult InsertStaff(@RequestBody Map map) throws ParseException {
        JsonResult jsonResult = new JsonResult();

        Staff staff = staffService.FindStaffByStaffPhone(map);
        Staff staff1 = staffService.FindStaffByStaffCard(map);
        if (staff == null&&staff1==null) {
            UploadController uploadController = new UploadController();
            String aimg = uploadController.GenerateImage(map);
            String staff_img = null;
            if (aimg.equals("添加失败")){
                staff_img = null;
            }else {
                staff_img = aimg;
            }
            map.put("staff_img",staff_img);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date now = new Date();
            String time = format.format(now);
            map.put("entry_time", time);
            if(map.get("staff_address").equals("")){
                map.put("staff_province","");
            }else {
                String staff_province = ProvinceUtil.Province((String) map.get("staff_address"));
                map.put("staff_province",staff_province);
            }
            int i = staffService.InsertStaff(map);
            if (i == 1) {
                jsonResult.setCode(200);
                jsonResult.setMessage("增加成功!");

            } else {
                jsonResult.setCode(20006);
                jsonResult.setMessage("增加失败!");

            }
        } else {
            jsonResult.setCode(2001);
            jsonResult.setMessage("员工已存在!");

        }

        return jsonResult;
    }

    @ApiOperation(value = "删除员工信息", notes = "{\"id\":2}")
    @PostMapping("/DeleteStaff")
    public boolean DeleteStaff(@RequestBody Map map) {
        return staffService.DeleteStaff(map) == 1;
    }

    @ApiOperation(value = "修改员工信息", notes = "")
    @PostMapping("/UpdateStaff")
    public boolean UpdateStaff(@RequestBody Map map) {
        System.out.println(map);
        return staffService.UpdateStaff(map) == 1;
    }

    @ApiOperation(value = "增加积分", notes = "")
    @PostMapping("/AddIntegral")
    public Msg AddIntegral(@RequestBody Map map) {
        Msg msg = new Msg();
        int i = staffService.AddIntegral(map);
        if(i==1){
            msg.setCode(200);
            msg.setMessage("增加成功!");
            return msg;
        }else {
            msg.setCode(20006);
            msg.setMessage("增加失败!");
            return msg;
        }
    }

    @ApiOperation(value = "分页模糊查询员工信息", notes = "{\"pageNo\":1,\"pageSize\":10}")
    @PostMapping("/FindStaff")
    public Page<Staff> FindStaff(@RequestBody Map map) {
        Page<Staff> page = new Page<Staff>();
        page.setPageNo((Integer) map.get("pageNo"));
        page.setPageSize((Integer) map.get("pageSize"));
        page.setTotal(staffService.Total(map));
        page.setItems(staffService.FindStaff(map));
        return page;
    }

    @ApiOperation(value = "批量导入", notes = "")
    @PostMapping("/import")
    public boolean addUser(@RequestParam("file") MultipartFile file,Integer user_id) throws Exception {
        Map map = new HashMap();
        map.put("user_id",user_id);
        boolean notNull = false;
        String fileName = file.getOriginalFilename();
        List<Staff> staffList = new ArrayList<Staff>();
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new MyException("上传文件格式不正确");
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        if (sheet != null) {
            notNull = true;
        }

        Staff staff;
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }

            row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
            String card1 = row.getCell(4).getStringCellValue();//身份证号
            if (card1.equals("")) {
                continue;
            }
            staff = new Staff();

            String name = row.getCell(0).getStringCellValue();//姓名
            row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
            String age = row.getCell(1).getStringCellValue();//年龄
            String sex = row.getCell(2).getStringCellValue();//性别
            String nation = row.getCell(3).getStringCellValue();//民族
            row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);//设置身份证号格式
            //String card1 = row.getCell(3).getStringCellValue();//身份证号
            //System.out.println("card1:" + card1);
            //System.out.println(card1.length());
            String card = null;
            if (card1.length() >= 18) {
                card = card1.substring(0, 18);
            }
            //System.out.println("card:" + card);
            String address = row.getCell(5).getStringCellValue();//地址
            row.getCell(6).setCellType(Cell.CELL_TYPE_STRING);//设置手机号格式
            String phone = row.getCell(6).getStringCellValue();//手机号
            String worktype_name = row.getCell(7).getStringCellValue();//工种

            //根据表格里面的内容判断worktype_id多少
            List<Worktype> worktypeList = worktypeService.SelectWorktype(map);
            int worktype_id = 0;
            for (int i = 0; i < worktypeList.size(); i++) {
                Worktype worktype = worktypeList.get(i);
                if (worktype.getWorktype_name().equals(worktype_name)) {
                    worktype_id = worktype.getId();
                }
            }

            String img = "default.jpg";

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date now = new Date();
            String time = format.format(now);

            String province = ProvinceUtil.Province(address);

            //添加到实体类
            staff.setStaff_name(name);
            staff.setStaff_age(age);
            staff.setStaff_img(img);
            staff.setStaff_sex(sex);
            staff.setStaff_nation(nation);
            staff.setStaff_card(card);
            staff.setStaff_address(address);
            staff.setStaff_phone(phone);
            staff.setWorktype_id(worktype_id);
            staff.setEntry_time(time);
            staff.setStaff_province(province);
            staff.setUser_id((Integer) map.get("user_id"));
            //添加到数组里
            staffList.add(staff);
        }
        for (Staff staff1 : staffList) {
            String staff_phone = staff1.getStaff_phone();
            //System.out.println("staff_phone:" + staff_phone);
            int cnt = staffService.CountStaff(staff_phone);
            if (cnt == 0) {
                staffService.InsertStaffS(staff1);
                System.out.println(" 插入 " + staff1.toString());
            } else {
                staffService.UpdateStaffS(staff1);
                System.out.println(" 更新 " + staff1.toString());
            }
        }
        return notNull;
    }

    @ApiOperation(value = "生成人员二维码" , notes = "")
    @PostMapping("/UpdateStaffCodes")
    public JsonResult UpdateStaffCodes(@RequestBody Map map) {
        JsonResult jsonResult = new JsonResult();
        try {
            String s = "http://www.pxkh888.com:8080/staff/staffMessage.html?user_id="+map.get("user_id")+"&staff_id="+map.get("id");

            CodePictureUtil codePictureUtil = new CodePictureUtil();//调用二维码实体类

            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
            Date now = new Date();
            String time = format.format(now);//获取当前时间

            int a = (int) map.get("id");
            String tempFileName = "staff_"+a+"_"+ time + ".jpg";
            map.put("codes" , tempFileName);

            //生成带文字的二维码
            //codePictureUtil.createWordQrcode("E:\\二维码图片\\"+tempFileName, "", s ,"", 400, 400);
            codePictureUtil.createWordQrcode("/root/examination/codes/"+tempFileName, "", s ,"", 400, 400);

            //添加二维码到数据库
            int i = staffService.UpdateStaffCodes(map);
            if (i==1){
                jsonResult.setCode(200);
                jsonResult.setMessage("生成成功!");
                return jsonResult;
            }else {
                jsonResult.setCode(20006);
                jsonResult.setMessage("生成失败!");
                return jsonResult;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        jsonResult.setCode(20006);
        jsonResult.setMessage("未生成!");
        return jsonResult;
    }

    @ApiOperation(value = "员工详细信息记录", notes = "{\"staff_id\":1}")
    @PostMapping("/FindStaffByAll")
    public JsonResult FindStaffByAll(@RequestBody Map map) {
        JsonResult jsonResult = new JsonResult();
        Staff staff = staffService.FindStaffByStaffId(map);
        //System.out.println(staff.getStaff_name());
        map.put("name",staff.getStaff_name());
        List<ExamRecord> examRecordList = examRecordService.FindExamRecordByStaffId(map);
        List<BehaviorRecord> behaviorRecordList = behaviorRecordService.FindBehaviorRecordByStaffIdALL(map);
        List<TrainContentRecord> trainContentRecordList = trainContentRecordService.FindContentRecordByName(map);
        jsonResult.setData(staff);
        jsonResult.setData2(examRecordList);
        jsonResult.setData3(trainContentRecordList);
        jsonResult.setData4(behaviorRecordList);
        return jsonResult;
    }

    @ApiOperation(value = "详细信息", notes = "{\"staffId\":1}")
    @PostMapping("/FindStaffBySid")
    public Msg FindStaffBySid(@RequestBody Map map) {
        Msg msg = new Msg();
        Staff staff = staffService.FindStaffBySid(map);
        msg.setData(staff);
        return msg;
    }

    @ApiOperation(value = "查找员工照片" , notes = "测试数据:{\"name\":\"安全行为之星系统.pdf\"}")
    @GetMapping("/find_img")
    public void find_img(@RequestParam String img_url, HttpServletResponse response) {
        try {
            BufferedInputStream bis =
                    new BufferedInputStream(
                            new FileInputStream(
                                    new File("F:/aaaa/" + img_url)));///root/img/
            int num;
            byte[] b = new byte[1024];

            while ((num = bis.read(b)) != -1) {
                response.getOutputStream().write(b, 0, num);
            }
            response.getOutputStream().flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
